package com.star.common.email.registrar;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Set;

/**
 * 启用email，自动扫描注册包com.star.common.email
 *
 * @author zhouhengzhe
 */
@Slf4j
@Configuration
public class EnableStarEmailRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        enableCzEmail(importingClassMetadata, registry);
    }

    public void enableCzEmail(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        String pkg = "com.star.common.email";
        ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
        scanner.setResourceLoader(new DefaultResourceLoader());
        scanner.addIncludeFilter(new AnnotationTypeFilter(Component.class));
        log.info("enable email starter");
        Set<BeanDefinition> candidates = scanner.findCandidateComponents(pkg);
        for (BeanDefinition candidate : candidates) {
            registry.registerBeanDefinition(Objects.requireNonNull(candidate.getBeanClassName()), candidate);
        }
    }
}
